package com.restaurant.springboot.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.restaurant.springboot.entity.WechatOpenIdResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @Author jack
 * @Date:2019/8/1 14:58
 */
@Component
public class HttpUtil {

    @Autowired
    RestTemplate restTemplate;

    /**
     *
     * @param url 链接
     * @param tClass 类型
     * @param parm 参数
     * @return 结果
     */
    public Object getResponseEntity(String url,Class tClass,Object ...parm) {
        Object wechatLoginResp = null;
        int try_time = 5;
        while(try_time >0 ) {
            try_time--;
            ObjectMapper mapper = new ObjectMapper();
            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class, parm);
            if (forEntity.getStatusCodeValue() == 200) {
                String response = forEntity.getBody();
                System.out.println(response);
                try {
                    wechatLoginResp = mapper.readValue(response, tClass);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return wechatLoginResp;
            }
        }
        return null;
    }
}
